<?php

namespace app\demo\controller;

use think\App;
use think\facade\Db;
use think\facade\View;

class Img extends Base
{
    // 图片处理demo
    public function index()
    {
        $sourceImagePath = "static/image/css.jpg";
        $res = $this->waterMark($sourceImagePath, "沉香亭北倚阑干");
        pp($res);
        echo('<img src="/' . $res . '">');
//        $param = request()->param();
//        $id = $param['id'] ?? 1;
//        $info = Db::table("bank")->where('id','=',$id)->find();
//        pp($info);

    }

    // 图片加水印
    private function waterMark($sourceImagePath, $text)
    {
        // 支持的图片格式
        $type = exif_imagetype($sourceImagePath);
        $fontSize = 16;
        $angle = 30;
        $fontFile = "static/src/fonts/msyhbd_slim.ttf";
        // 根据图片类型选择不同的读取函数
        switch ($type) {
            case IMAGETYPE_JPEG:
                $img = imagecreatefromjpeg($sourceImagePath);
                break;
            case IMAGETYPE_PNG:
                $img = imagecreatefrompng($sourceImagePath);
                break;
            case IMAGETYPE_BMP:
                $img = imagecreatefromwbmp($sourceImagePath);
                break;
            case IMAGETYPE_WEBP:
                if (function_exists('imagecreatefromwebp')) {
                    $img = imagecreatefromwebp($sourceImagePath);
                } else {
                    trigger_error('暂不支持webp格式', E_USER_ERROR);
                }
                break;
            case IMAGETYPE_GIF:
                $img = imagecreatefromgif($sourceImagePath);
                break;
            default:
                trigger_error('暂不支持的格式', E_USER_ERROR);
        }

        // 获取图片的尺寸
        $width = imagesx($img);
        $height = imagesy($img);

        $startX = 50;
        $startY = 100;
        $spacingX = 200;
        $spacingY = 200;

//        pp([
//            'width' => $width,
//            'height' => $height,
//            'startX' => $startX,
//            'startY' => $startY,
//            'spacingX' => $spacingX,
//            'spacingY' => $spacingY,
//        ]);

        // 设置水印的颜色
//        $white = imagecolorallocate($img, 255, 255, 255);
        $white = imagecolorallocatealpha($img, 144, 144, 144,70);
        // 计算水印的位置
        for ($y2 = $startY; $y2 < $height; $y2 += $spacingY) {
            for ($x2 = $startX; $x2 < $width; $x2 += $spacingX) {
                // 添加水印
                imagettftext($img, $fontSize, $angle, $x2, $y2, $white, $fontFile, $text);
            }
        }
        $targetImagePath = 'tmp/' . create_unique_number() . ".jpg";
        create_dir($targetImagePath);
        // 保存为JPEG格式
        imagejpeg($img, $targetImagePath, 80); // 第三个参数是质量，范围0-100
        // 释放资源
        imagedestroy($img);
//        @unlink($sourceImagePath); // 删除源文件, 返回新文件路径
        return $targetImagePath;
    }


}
